#pragma once

#include <iostream>
#include <cstring>
#include <string>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include "log.hpp"

using namespace std;

Log log;
const string path = "/home/user3";
const int proj_id = 0x114514;
const size_t MSIZE = 4096;


key_t Getkey()
{
    key_t key = ftok(path.c_str(), proj_id);
    if (key == -1)
    {
        log(Fatal, "ftok fail! errstring: %s, err code: %d", strerror(errno), errno);
        exit(1);
    }
    log(Info, "ftok Success! key : %d", key);
    return key;
}

int GetShareMemHeper(int flag)
{
    key_t key = Getkey();
    int md = shmget(key, MSIZE, flag);
    if (md == -1)
    {
        log(Fatal, "shmet fail! errstring: %s, err code: %d", strerror(errno), errno);
        exit(2);
    }
    log(Info, "shmget Success! shmid : %d", md);
    return md;
}

int CreateShm()
{
    return GetShareMemHeper(IPC_CREAT | IPC_EXCL | 0666);
}

int GetShm()
{
    return GetShareMemHeper(IPC_CREAT);
}
